import { Card, Form, Input, Button, Select, Table, Image, message } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import { useEffect, useState } from 'react'
import { ColumnsType } from 'antd/lib/table'
import {
  reqGetHospitalList,
  reqGetProvinceiList,
  reqGetCityOrQuXianList,
  reqUpdateHospitalStatus
} from '@api/hospital/hospitalList'
import {
  HospitalListType,
  HospitalItemType,
  Status,
  ProvinceList,
} from '@api/hospital/model/hospitalListTypes'
import { useNavigate } from 'react-router-dom'

const { Option } = Select

export default function HospitalList() {
  // 声明状态
  const [hospitalList, setHospitalList] = useState<HospitalListType>([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)
  const [bool, setBool] = useState(false)

  // 声明省列表的数据
  const [provinceList, setProvinceList] = useState<ProvinceList>([])
  // 声明城市列表的数据
  const [cityList, setCityList] = useState<ProvinceList>([])
  // 声明区县的数据
  const [quxianList, setQuxianList] = useState<ProvinceList>([])
  // 声明医院类型的数据
  const [hosTypeList, setHosTypeList] = useState<ProvinceList>([])

  // 请求医院列表数据
  async function getHospitalList(page = current, limit = pageSize) {
    // console.log(form.getFieldsValue());
    // 先获取收集的表单数据
    const values = form.getFieldsValue()

    setBool(true)
    const res = await reqGetHospitalList({ page, limit, ...values })
    // console.log(res)

    setBool(false)
    // 设置数据
    setHospitalList(res.content)
    // 设置总条数
    setTotal(res.totalElements)
    setCurrent(page)
    setPageSize(limit)
  }

  useEffect(() => {
    // 请求省份的数据
    ;(async () => {
      const res = await reqGetProvinceiList()
      console.log(res)
      setProvinceList(res)
    })()

    // 获取医院类型的数据
    ;(async () => {
      const res = await reqGetCityOrQuXianList(10000)
      setHosTypeList(res)
    })()

    getHospitalList()
  }, [])

  // 声明一个form对象 - 创建一个实例对象，就可以调用方法
  const [form] = Form.useForm()
  // 当省份的数据改变，则请求城市列表
  async function getCityList(id: number) {
    const res = await reqGetCityOrQuXianList(id)
    setCityList(res)

    // 清空市区的信息
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined })
    // 清空区县的数据
    setQuxianList([])
  }
  // 当市区的数据改变，则请求区县列表
  async function getAreaList(id: number) {
    const res = await reqGetCityOrQuXianList(id)
    setQuxianList(res)
    // 清空区县的数据
    form.setFieldsValue({ districtCode: undefined })
  }

  // 清空表单并重新加载数据
  function resetForm() {
    // 清空表单的字段
    form.resetFields()
    setCityList([])
    setQuxianList([])
    // 重新获取数据
    getHospitalList(1, 5)
  }

  // 改变上下线的状态
  async function changeStatus(id: any, sta: any) {
    await reqUpdateHospitalStatus(id, sta)
    message.success('更新状态成功');
    // 状态更新之后重新请求数据
    getHospitalList(current, pageSize);
  }

  // 声明编程式导航的方法
  const navigate = useNavigate()

  // 声明表格的列数据
  const columns: ColumnsType<any> = [
    {
      title: '序号',
      width: 100,
      align: 'center',
      render(value, row, index) {
        return index + 1
      },
    },
    {
      title: '医院logo',
      width: 120,
      dataIndex: 'logoData',
      render(logo: string) {
        // base64位的图片，一定要加上前缀，以后不一定这么写
        // 取决于后端返回的数据格式是咋样的
        return <Image src={`data:image/jpg;base64,${logo}`} />
      },
    },
    {
      title: '医院名称',
      width: 260,
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      width: 120,
      render(row: HospitalItemType) {
        return row.param.hostypeString
      },
    },
    {
      title: '详细地址',
      width: 240,
      // 默认 dataIndex 只能接收单个字段，如果有打点的，需要写成 render
      render(row: HospitalItemType) {
        return row.param.fullAddress
      },
    },
    {
      title: '状态',
      // 既保留单条数据，也动态改变文本
      dataIndex: 'status',
      width: 120,
      render(status: Status) {
        return status ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      width: 240,
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      width: 265,
      fixed: 'right',
      render(row) {
        return (
          <>
            <Button
              type="primary"
              onClick={() => navigate(`/syt/hospital/detail/${row.id}`)}
            >
              查看
            </Button>
            <Button type="primary" className="ml"
            onClick={() => navigate(`/syt/hospital/schedule/${row.hoscode}`)}
            >
              排班
            </Button>
            <Button 
              type="primary" 
              danger={Boolean(row.status)}
              className="ml"
              onClick={() => changeStatus(row.id, row.status ? 0 : 1)}
            >
              { row.status ? '下线' : '上线'}
            </Button>
          </>
        )
      },
    },
  ]

  return (
    <Card>
      {/* 1. 搜索表单 */}
      <Form form={form} layout="inline" className="hos-list">
        <Form.Item name="provinceCode">
          {/* 只能写行内的样式 */}
          <Select
            placeholder="请选择省份"
            style={{ width: 180 }}
            onChange={getCityList}
          >
            {provinceList.map((item) => {
              return (
                <Option value={item.value} key={item.id}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            placeholder="请选择市区"
            style={{ width: 180 }}
            onChange={getAreaList}
          >
            {cityList.map((item) => {
              return (
                <Option value={item.value} key={item.id}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select placeholder="请选择区县" style={{ width: 180 }}>
            {quxianList.map((item) => {
              return (
                <Option value={item.value} key={item.id}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item name="hostype">
          <Select placeholder="请选择医院类型" style={{ width: 180 }}>
            {hosTypeList.map((item) => {
              return (
                <Option value={item.value} key={item.id}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            placeholder="请选择医院状态"
            style={{ width: 180 }}
            options={[
              {
                value: 0,
                label: '未上线',
              },
              {
                value: 1,
                label: '已上线',
              },
            ]}
          />
        </Form.Item>
        <Form.Item>
          <Button
            onClick={() => getHospitalList()}
            type="primary"
            htmlType="submit"
            icon={<SearchOutlined />}
          >
            查询
          </Button>
          <Button onClick={resetForm} className="ml">清空</Button>
        </Form.Item>
      </Form>

      {/* 2. 表格渲染 */}
      {/* rowSelection 提供表格的选择工具 */}
      <Table
        style={{ marginTop: 20 }}
        columns={columns}
        dataSource={hospitalList}
        bordered
        rowKey="id"
        scroll={{ x: 1500 }}
        // 除了字符之外，所有的数据都需要加 {}
        loading={bool}
        pagination={{
          current,
          total,
          pageSize,
          showSizeChanger: true,
          pageSizeOptions: [5, 10, 15],
          showQuickJumper: true,
          showTotal: (total) => `总共${total}条`,

          // onChange: 当页码更新或者数量更新，会重新执行
          onChange: getHospitalList,
        }}
      />
    </Card>
  )
}
